
package com.attilax.user;

import java.io.File;
import java.util.List;
import java.util.Map;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.web.filter.CharacterEncodingFilter;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.attilax.anno.Inj;
import com.attilax.db.DBX;
import com.attilax.db.DbServiceV4qb9;
import com.attilax.db.SqlAstBuilderP32;
import com.attilax.fieldMap.FieldMapper;
import com.attilax.io.pathx;
import com.attilax.ioc.Ioc4wash;
import com.attilax.net.HttpUtil;
import com.attilax.sql.DbMetaService;
import com.attilax.sql.SqlService;
import com.attilax.sql.Sqlbuilder;

import com.attilax.util.JsonFieldMapper;
import com.attilax.util.PropX;
import com.google.inject.Inject;

import aaaPKg.Doc360docPubber;

@SuppressWarnings("all")
public class UserSync4jonlye {

	@Inject
	DbServiceV4qb9 dbsvr1;

	@Inject
	DbMetaService DbMetaSvr1;

	@Inject
	Sqlbuilder Sqlbuilder1;

	@Inject
	DbMetaService metaSvr;

	public static void main(String[] args) {
		logger.debug("--dbg");
//		SqlService   sqls=	Ioc4wash.getBean(SqlService.class);
//		DBX dx=	Ioc4wash.getBean(DBX.class);
//		DbMetaService dbc=		Ioc4wash.getBean(DbMetaService.class);
		//CharacterEncodingFilter
	//	org.springframework.web.filter.CharacterEncodingFilte
		UserSync4jonlye usj = Ioc4wash.getBean(UserSync4jonlye.class);
		usj.sync();
		 usj.syncDepart();
	}

	// user sysnc
	private void sync() {
		iniUrl();
		String jsonStr = HttpUtil.sendGetV2(url, "utf8");
		JSONObject jo = JSON.parseObject(jsonStr);
		JSONArray usrs = jo.getJSONObject("result").getJSONArray("deptMembers");
		Long   savepointID = (Long) jo.getJSONObject("result").get("timestamp"); 
		int endindex = usrs.size();
		setPoint(endindex, "usersync",savepointID.toString());

		String table = "s_member";
		String prikey = metaSvr.getPrimaryKey(table);
		List ColumnsDefs = metaSvr.getColumns(null, table);
		Sqlbuilder1.prikey = prikey;
		Sqlbuilder1.ColumnsDefs = ColumnsDefs;
		int n = 0;
		for (Object object : usrs) {
			n++;
			Map jo1 = (Map) object;
			String filedMapTable_String = "user.email:email,user.werks:unit_id,user.zwtype:duties_id,displayName:name,duty.dutyName:department,user.plansTxt :duties_name,deptId:department_id,user.phone:phone,user.id:member_no";
			Map m = FieldMapper.map(jo1, filedMapTable_String, new  PropConverter());

			// ,department=values(department)
			String mergeUpdateExpress = Sqlbuilder1.getMergeUpdateExpress(
					"duties_id,duties_id,duties_name,department,unit_id,email,department_id,phone");
			String sql = Sqlbuilder1.toMergeSql_hiPerf(m, "s_member", mergeUpdateExpress);
			System.out.println(n + "," + sql);
			try {
				int ri = dbsvr1.executeUpdate(sql);
				logger.info("cnt:" + n + ",retEffectInt:" + ri + " ," + sql);
			} catch (Exception e) {
				logger.error("syncMember", e);
			}
			try {
				upPoint(n,endindex,"usersync",savepointID.toString());
			} catch (Exception e) {
				logger.error("syncMember", e);
			}
		
			

		}
		// JSONArray dpts = jo.getJSONObject("result").getJSONArray("depts");

	}
	private void iniUrl() {

			String f = pathx.webinfDir()+File.separator+"config.properties";
			PropX px=new PropX( f);
		url=px.getProperty("usersyncUrl").trim();
			
	}

	private void setPoint(  int endindex, String rectype,String savepointID) {
		String sql = "	insert savepointx(rectype,endindex,savepointID)values('@rectype@',@endindex@,'@outer_index@')  ON DUPLICATE KEY UPDATE  endindex=values(endindex)";
	//	sql = sql.replace("@curindex@", String.valueOf(n));
		sql = sql.replace("@endindex@", String.valueOf(endindex));
		sql = sql.replace("@rectype@", rectype);
		sql = sql.replace("@outer_index@", savepointID);
		
		try {
			int ri = dbsvr1.executeUpdate(sql);
			logger.info("savePoint endindex:" + endindex + "outer_index:"+savepointID+" ,retEffectInt:" + ri + " ," + sql);
		} catch (Exception e) {
			logger.error("syncMember", e);
		}
	}
	private void upPoint(int n, int endindex, String rectype,String savepointID) {
		String sql = "	update savepointx set curindex=@curindex@ where rectype='@rectype@' and   savepointID='@savepointID@'  ";
		sql = sql.replace("@curindex@", String.valueOf(n));
		sql = sql.replace("@endindex@", String.valueOf(endindex));
		sql = sql.replace("@rectype@", rectype);	sql = sql.replace("@savepointID@", savepointID);
		try {
			int ri = dbsvr1.executeUpdate(sql);
			logger.info("savePoint curindex:" + n + ",retEffectInt:" + ri + " ," + sql);
		} catch (Exception e) {
			logger.error("syncMember", e);
		}
	}

	public static Logger logger = LoggerFactory.getLogger(UserSync4jonlye.class);
	String url = "	http://10.39.52.121:8000/ehr/user/sync/0.jhtml";

	private void syncDepart() {
		iniUrl();
		String jsonStr = HttpUtil.sendGetV2(url, "utf8");
	//	String jsonStr = HttpUtil.sendGetV2(url, "utf8");
		JSONObject jo = JSON.parseObject(jsonStr);
		List<Object> lst = jo.getJSONObject("result").getJSONArray("depts");
		// List<Map> lst=lst2;
		String table = "l_department";
		String prikey = metaSvr.getPrimaryKey(table);
		List ColumnsDefs = metaSvr.getColumns(null, table);
		Sqlbuilder1.prikey = prikey;
		Sqlbuilder1.ColumnsDefs = ColumnsDefs;
		int n = 0;
		for (Object obj1 : lst) {
			Map obj_map = (Map) obj1;
			String filedMapTable_String = "deptName:title,id:dptno,parentId:dptpid";

			Map m = FieldMapper.map(obj_map, filedMapTable_String, new  PropConverter());

			String sql = Sqlbuilder1.toInsertSql_hiPerf(m, table);
			n++;
			System.out.println("no:" + n + sql);

			try {
				dbsvr1.executeUpdate(sql);
			} catch (Exception e) {
				logger.error("syncDepart", e);
			}

		}

	}

	public Map fmtConvert(Map m) {
		// status : ""
		if (m.get("status") != null)
			if (m.get("status").equals("ENABLED"))
				m.put("status", 1);
			else
				m.put("status", 2);
		return m;
	}

}
